<!DOCTYPE html>
<html>

<head>
    <meta charset="utf8">
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <!-- 引入ladash库进行函数限流 -->
    <script src="https://unpkg.com/lodash@4.17.20/lodash.min.js"></script>
</head>

<body>
    <div id="myapp">
        <button @click="get_time_ladash">当前时间</button>
    </div>
</body>
<script>
    const app = {
        data() {
            return {
                // 定义一个变量来控制是否限流
                throttle: false,
            }
        },
        methods: {
            get_time() {
                //不进行封装
                // if (!this.throttle) {
                //     alert(Date().toString());
                // }
                // else {
                //     return;
                // }
                // this.throttle = true;
                // setTimeout(() => {
                //     this.throttle = false;
                // }, 2000)
                //封装后
                // ()={}好像是类似于C++得lambda表达式 但是没有类型限制?这么爽
                throttle_tool(() => { alert(Date()) }, 2000);
            },
            //使用ladash库限流不一样是点了等timeout在执行,重复点就重置计时器
            get_time_ladash: _.debounce(() => { alert(Date()) }, 2000)

        }
    }

    // 将限流逻辑封装
    var throttle = false;
    function throttle_tool(callback, timeout) {
        // 如果不限流就调用回调函数
        if (!throttle) {
            callback();
        }
        //否则限流
        else {
            return;
        }
        //调用以后设置限流条件
        throttle = true;
        //设置Timeout自动接触限流
        //自带函数 (function, timeout毫秒)
        setTimeout(() => { throttle = false; }, timeout)
    }
    let instance = Vue.createApp(app).mount("#myapp");
</script>

</html>